package cate.game.server.rpc;

import cate.game.common.rpc.RpcListener4Game;
import cate.game.common.rpc.RpcListener4Process;
import cp.solution.rpc.RpcMsgHead;
import cp.solution.rpc.bridge.FaxBridge;
import fax.client.handler.StandardFaxClientHandler;
import fax.common.react.FaxSink;
import fax.common.route.RouteMeta;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FaxClientHandler extends StandardFaxClientHandler {

    List<RpcListener4Game> items = new ArrayList<>();

    public void regForGame(RpcListener4Game item) {
        items.add(item);
    }

    RpcListener4Process pItem;
    public void regForProcess(RpcListener4Process item) {
        this.pItem = item;
    }

    @Override
    public void fireAndForget(RouteMeta routeMeta, byte[] bytes) throws Exception {
        log.debug("收到<fireAndForget> {}", routeMeta);
        RpcMsgHead head = FaxBridge.fromMeta(routeMeta);
        if(RpcListener4Game.awarePath(head.path())) {
            for(RpcListener4Game item : items) {
                if(item.accept(head)) {
                    item.dispatchFireAndForget(head, bytes);
                }
            }
        } else if(RpcListener4Process.awarePath(head.path())){
            pItem.dispatchFireAndForget(head, bytes);
        } else {
            log.warn("收到未注册事件{}", head.path());
        }
    }

    @Override
    public Object requestResponse(RouteMeta routeMeta, byte[] bytes) throws Exception {
        log.debug("收到<requestResponse> {}", routeMeta);
        RpcMsgHead head = FaxBridge.fromMeta(routeMeta);
        if(RpcListener4Game.awarePath(head.path())) {
            for(RpcListener4Game item : items) {
                if(item.accept(head)) {
                    return item.dispatchRequestResponse(head, bytes);
                }
            }
        } else if(RpcListener4Process.awarePath(head.path())){
            return pItem.dispatchRequestResponse(head, bytes);
        } else {
            log.warn("收到未注册事件{}", head.path());
        }
        //return games.logic.faxDispatcher.doRequestResponse(game, codec, routeMeta, bytes);
        return null;
    }

    @Override
    public void requestStream(RouteMeta routeMeta, byte[] bytes, FaxSink faxSink) throws Exception {
        log.debug("收到<requestStream> {}", routeMeta);
    }

}
